package com.atguigu.srb.base.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;

/**
 * ClassName: RedisConfig
 * Package: com.atguigu.srb.base.config
 * Description:
 *
 * @Author 王晓龙
 * @Create 2023/3/29 16:27
 * @Version 1.0
 */
@Configuration
@EnableCaching //开启缓存功能
public class RedisConfig {
    @Resource
    RedisTemplate redisTemplate;
    @PostConstruct //依赖注入完成后，执行初始化方法，该方法必定执行
    //当前类对象初始化后 给装配的redisTemplate配置键和值的序列化器
    public void init(){
        //设置key的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //设置value的序列化方式
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    }

    //创建缓存管理器
    @Bean
    public CacheManager cacheManager(LettuceConnectionFactory lettuceConnectionFactory){
        RedisCacheConfiguration configuration = RedisCacheConfiguration
                .defaultCacheConfig() //设置默认配置
                .entryTtl(Duration.ofMinutes(2))
                .disableCachingNullValues()
                .serializeKeysWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new GenericJackson2JsonRedisSerializer()));
        //创建缓存管理器
        return RedisCacheManager
                .builder(lettuceConnectionFactory) //通过工厂构建
                .cacheDefaults(configuration) //使用上面自定义的缓存管理器
                .build();
    }
}
